package edu.indiana.d2i.ontology.exec;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;

import edu.indiana.d2i.ontology.AbstractSQLExec;
import edu.indiana.d2i.ontology.util.AccessDBUtil;
import edu.indiana.d2i.ontology.util.Constants;

/**
 * This class overrides methods addDataProperties, addObjectProperties, 
 * and setData2JenaModel, just because it tries to save some SQL query cost.
 */
public class PInfo extends AbstractSQLExec {
	protected int organID = -1; 

	public PInfo(AccessDBUtil dbCon, OntModel model, int id, String subjectURI) {
		super(dbCon, model, id, subjectURI);
	}

	@Override
	protected void addDataProperties(String sql) {		
		assert resourceURI != null;
		
		try {
			ResultSet resultSet = dbCon.query(sql);
			if (resultSet.next()) {
				ResultSetMetaData metaData = resultSet.getMetaData();
				
				int colCount = metaData.getColumnCount();
				for (int i = 1; i <= colCount; i++) {
					String columnName = metaData.getColumnName(i);
					// keep the organ id to avoid another SQL query
					if (columnName.equals("FK_F_ORGAN")) 
						organID = Integer.valueOf(resultSet.getString(columnName)); 
					// ignore the foreign key and ID fields
					if (columnName.equals("ID") || columnName.startsWith("FK_")) 
						continue;
					
					String tmp = resultSet.getString(columnName);
					DatatypeProperty pHasValue = model.createDatatypeProperty(nameSpace + "has_" + columnName);
					if (tmp == null) tmp = "";
					model.add(individual, pHasValue, tmp);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void addObjectProperties(String subjectURI) {
		// add parent object properties
		if (subjectURI != null) {
			ObjectProperty pHasParentRelation = model.getObjectProperty(Constants.HAS_RELATIONSHIP);
			model.add(individual, pHasParentRelation, model.getIndividual(subjectURI));
		}
		
		// no children needs to be addednName));
	}
	
	@Override
	public void setData2JenaModel() {
		assert sqlStatement != null;
		
		// add data properties				
		this.addDataProperties(sqlStatement);
		
		// add object properties
		this.addObjectProperties(subjectURI);
	}
}
